#!/bin/bash

# partition size in MB
LOAD_RESERVE=4
BOOT_SIZE=16
MISC_SIZE=200
RTFS_SIZE=500
APPS_SIZE=200
CFGS_SIZE=200
LOGA_SIZE=8
LOGB_SIZE=8
# DISK_SIZE=



node="na"

[ $# -eq 1 ] && node=$1

if [ ! -e ${node} ]; then
	exit 1
fi

sfdisk_version=`sfdisk -v | awk '{print $4}' | awk -F '.' '{print $2}'`
if [ $sfdisk_version -ge "26" ]; then
     opt_unit=""
     unit_mb="M"
else
     opt_unit="-uM"
     unit_mb=""
fi

# call sfdisk to create partition table
# get total card size
seprate=40
total_size=`sfdisk -s ${node}`
total_size=`expr ${total_size} / 1024`
boot_sizeb=`expr ${BOOT_SIZE} + ${LOAD_RESERVE}`
extend_size=`expr ${RTFS_SIZE} + ${APPS_SIZE} + ${CFGS_SIZE} + ${LOGA_SIZE} + ${LOGB_SIZE} + ${seprate}`
disk_size=`expr ${total_size} - ${boot_sizeb} - ${MISC_SIZE} - ${extend_size}`

# show partitions
cat << EOF
======== partitions ======
LOAD   : ${LOAD_RESERVE}MB
BOOT   : ${BOOT_SIZE}MB
MISC   : ${MISC_SIZE}MB
RTFS   : ${RTFS_SIZE}MB
APPS   : ${APPS_SIZE}MB
CFGS   : ${CFGS_SIZE}MB
LOGA   : ${LOGA_SIZE}MB
LOGB   : ${LOGB_SIZE}MB
DISK   : ${disk_size}MB
==========================
EOF

# destroy the partition table
dd if=/dev/zero of=${node} bs=1024 count=1

sfdisk --force ${opt_unit} ${node} << EOF
,${boot_sizeb}${unit_mb},83
,${MISC_SIZE}${unit_mb},83
,${extend_size}${unit_mb},5
,${disk_size}${unit_mb},c
,${RTFS_SIZE}${unit_mb},83
,${APPS_SIZE}${unit_mb},83
,${CFGS_SIZE}${unit_mb},83
,${LOGA_SIZE}${unit_mb},83
,${LOGB_SIZE}${unit_mb},83
EOF


sfdisk --force ${opt_unit} ${node} -N1 << EOF
${LOAD_RESERVE}${unit_mb},${BOOT_SIZE}${unit_mb},83
EOF
